package mirrormonkey.util.netevent.client.tools;

import java.util.LinkedList;
import java.util.List;

import org.junit.Assert;

import com.jme3.network.Client;
import com.jme3.network.ClientStateListener;

/**
 * Tracks connected and disconnected <tt>Client</tt>s and provides methods
 * to check if the right events were received.
 * 
 * @author Philipp Christian Loewner
 * 
 */
public class MockClientStateListener implements ClientStateListener {

	private final List<Client> connected = new LinkedList<Client>();

	private final List<Disconnect> disconnected = new LinkedList<Disconnect>();

	@Override
	public void clientConnected(Client client) {
		connected.add(client);
	}

	@Override
	public void clientDisconnected(Client client, DisconnectInfo info) {
		disconnected.add(new Disconnect(client, info));
	}

	public void checkConnected(Client[] clients) {
		Assert.assertEquals(clients.length, connected.size());
		int i = 0;
		for (Client c : connected) {
			Assert.assertSame(c, clients[i++]);
		}
	}

	public static void checkConnected(MockClientStateListener[] listeners,
			Client[] clients) {
		for (MockClientStateListener l : listeners) {
			l.checkConnected(clients);
		}
	}

	public void checkDisconnected(Client[] clients, DisconnectInfo[] info) {
		Assert.assertEquals(clients.length, disconnected.size());
		int i = 0;
		for (Disconnect d : disconnected) {
			Assert.assertSame(clients[i], d.c);
			Assert.assertSame(info[i], d.info);
			i++;
		}
	}

	public static void checkDisconnected(MockClientStateListener[] listeners,
			Client[] clients, DisconnectInfo[] info) {
		for (MockClientStateListener l : listeners) {
			l.checkDisconnected(clients, info);
		}
	}

	public static void reset(MockClientStateListener[] listeners) {
		for (MockClientStateListener l : listeners) {
			l.connected.clear();
			l.disconnected.clear();
		}
	}

	public static final class Disconnect {

		public final Client c;

		public final DisconnectInfo info;

		public Disconnect(Client c, DisconnectInfo info) {
			this.c = c;
			this.info = info;
		}

	}

}
